from http.server import BaseHTTPRequestHandler, HTTPServer
import os
import cgi
import urllib.parse

class FileHandler(BaseHTTPRequestHandler):
    file_directory = "."  # File storage directory

    def do_GET(self):
        parsed_path = urllib.parse.urlparse(self.path)
        params = urllib.parse.parse_qs(parsed_path.query)

        if 'filename' in params:
            filename = params['filename'][0]
            file_path = os.path.join(self.file_directory, filename)
            if os.path.exists(file_path) and os.path.isfile(file_path):
                self.send_response(200)
                self.send_header('Content-type', 'application/octet-stream')
                self.send_header('Content-Disposition', 'attachment; filename=' + os.path.basename(file_path))
                self.end_headers()
                with open(file_path, 'rb') as file:
                    self.wfile.write(file.read())
            else:
                self.send_response(404)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(b'File not found.')
        else:
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            files = os.listdir(self.file_directory)
            file_links = ["<li><a href='/?filename={0}'>{0}</a></li>".format(file) for file in files]
            html = """
                <html>
                <body>
                <h1>File upload</h1>
                <form action="/" enctype="multipart/form-data" method="post">
                <input type="file" name="file" accept="*/*">
                <input type="submit" value="Upload">
                </form>
                <h1>Files on server</h1>
                <ul>
                {0}
                </ul>
                <div><p><strong>curl post method:</strong> curl -X POST -F "file=@./tasks.json" -F "filename=tasks.json" http://localhost:8000/</p>
                     <p><strong>curl get method:</strong> curl -o tasks.json http://localhost:8000/?filename=tasks.json</p>
                </div>
                </body>
                </html>
            """.format("\n".join(file_links))
            self.wfile.write(html.encode())


    def do_POST(self):
        form = cgi.FieldStorage(
            fp=self.rfile, 
            headers=self.headers,
            environ={
                'REQUEST_METHOD': 'POST',
                'CONTENT_TYPE': self.headers['Content-Type'],
            },
        )

        # Check if the file field is present
        if 'file' not in form:
            self.send_response(400)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'File field is missing.')
            return

        file_item = form['file']

        # Check if the field contains an uploaded file
        if not file_item.file:
            self.send_response(400)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(b'No file uploaded.')
            return

        # Get the filename from the file field or from a separate filename field
        if 'filename' in form:
            filename = form['filename'].value
        else:
            filename = file_item.filename if file_item.filename else 'unknown_filename'

        file_path = os.path.join(self.file_directory, filename)

        with open(file_path, 'wb') as file:
            data = file_item.file.read()
            file.write(data)

        self.send_response(201)
        self.send_header('Content-type', 'text/html')
        self.end_headers()
        self.wfile.write(b'File uploaded successfully.')







def run_server(port):
    server_address = ('', port)
    httpd = HTTPServer(server_address, FileHandler)
    print(f'Starting file server on port {port}...')
    httpd.serve_forever()


if __name__ == '__main__':
    run_server(8000)
